package sskj.regulatory.presentation.widget

import android.app.AlertDialog
import android.content.Context
import android.net.http.SslError
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.AttributeSet
import android.view.KeyEvent
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.WebView
import android.widget.ProgressBar
import sskj.regulatory.R


@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class ProgressWebView(context: Context, attrs: AttributeSet) : WebView(context, attrs) {

    private val progressbar: ProgressBar = ProgressBar(context, null,
            android.R.attr.progressBarStyleHorizontal)

    init {
        progressbar.layoutParams = LayoutParams(LayoutParams.FILL_PARENT,
                6, 0, 0)

        progressbar.progressDrawable = context.resources.getDrawable(R.drawable.progress_bar_states, resources.newTheme())
        addView(progressbar)
        webChromeClient = WebChromeClient()
        settings.setSupportZoom(true)
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.builtInZoomControls = false
        settings.displayZoomControls = false
        settings.setSupportMultipleWindows(false)


    }

    inner class WebChromeClient : android.webkit.WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                progressbar.visibility = GONE
            } else {
                if (progressbar.visibility === GONE)
                    progressbar.visibility = VISIBLE
                progressbar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }

        override fun onJsAlert(view: WebView, url: String, message: String,
                               result: JsResult): Boolean {
            val builder = AlertDialog.Builder(view.context)

            builder.setTitle("对话框")
                    .setMessage(message)
                    .setPositiveButton("确定", null)

            // 禁止响应按back键的事件
            builder.setCancelable(false)
            val dialog = builder.create()
            dialog.show()
            result.confirm()// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
            return true
            // return super.onJsAlert(view, url, message, result);
        }
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        val lp = progressbar.layoutParams as LayoutParams
        lp.x = l
        lp.y = t
        progressbar.layoutParams = lp
        super.onScrollChanged(l, t, oldl, oldt)
    }
}